/** @jsxImportSource @emotion/react */
import * as React from "react";
import {css} from "@emotion/react";
import {
    Button,
    InputLine,
    Input,
    TextArea,
    Select,
    InputDatalist,
    Text,
    CheckSwitch,
    SuffixInput,
    useTheme,
    LineColumn, Layer, Table, TableHead, TableRow, CCell, TableBody, Cell,
} from "customize-easy-ui-component";
import {
    InspectRecordLayout,InternalItemProps, SelectHookfork, SelectInput,useItemInputControl
} from "../../common/base";
import {Each_ZdSetting, useRepTableEditor, useTableEditor} from "../../hook/useRepTableEditor";
import { useMeasureInpFilter} from "../../common/hooks";
import '@uppy/core/dist/style.min.css';
import '@uppy/dashboard/dist/style.min.css';
import '@uppy/webcam/dist/style.min.css';
// import {useUppyUpload} from "../../hook/useUppyUpload";
import {EditStorageContext} from "../../StorageContext";
import {itemResultUnqualified} from "../../common/config";
import {setupItemAreaRoute} from "./orcIspConfig";
import {特殊项目编码} from "./FormatOriginal";

export const 现场结果选=["符合要求","不符合要求"];
//下结论页面：
export const ItemConclusionCr=
    React.forwardRef((
        { children, show ,alone=true,refWidth}:InternalItemProps,  ref
    ) => {
        const theme = useTheme();
        const getInpFilter = React.useCallback((par: any) => {
            const {检验结论,检验日期,新下检日,无雨雪,检验场地,应清洁,大备注} =par||{};
            return {检验结论,检验日期,新下检日,无雨雪,检验场地,应清洁,大备注};
        }, []);
        const {inp, setInp} = useItemInputControl({ ref });
        const [floor, setFloor] = React.useState<string|null>(null);
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}
                                 alone={alone}  label={'六、结论；七、备注 附录B：现场检验条件'} column={0}>
                <Text  variant="h5">
                    附录B：现场检验条件确认
                </Text>
                1、露天检验应在无雨雪情况下进行；<br/>
                2、检验现场环境符合相关标准中对检验场地的要求；<br/>
                3、检验现场（主要指试验场地、车辆检验场地等）应清洁，不应有与叉车检验无关的物品和设备，并应放置表明现场正在进行检验的警示牌。
                <LineColumn column={2} >
                    <InputLine  label='1、无雨雪:' >
                        <SelectInput value={ inp?.无雨雪 ||''} onChange={e => setInp({ ...inp, 无雨雪: e.currentTarget.value||undefined}) }
                                     list={现场结果选} />
                    </InputLine>
                    <InputLine  label='2、场地环境:' >
                        <SelectInput value={ inp?.检验场地 ||''} onChange={e => setInp({ ...inp, 检验场地: e.currentTarget.value||undefined}) }
                                     list={现场结果选} />
                    </InputLine>

                    <InputLine  label='3、现场应清洁:' >
                        <SelectInput value={ inp?.应清洁 ||''} onChange={e => setInp({ ...inp, 应清洁: e.currentTarget.value||undefined}) }
                                     list={现场结果选} />
                    </InputLine>
                </LineColumn>
                <hr/>
                <Text  variant="h5">
                    六、综合结论 (报告下结论)：
                </Text>
                <InputLine  label='六、综合结论' >
                    <Select inputSize="md" css={{minWidth:'140px',fontSize:'1.3rem',padding:'0 1rem'}}
                            value={ inp?.检验结论  ||''}
                            onChange={e => setInp({ ...inp, 检验结论: e.currentTarget.value||undefined}) }
                    >
                        <option></option>
                        <option>合格</option>
                        <option>不合格</option>
                    </Select>
                </InputLine>
                <InputLine  label='设置检验日期' >
                    <Input  value={inp?.检验日期 ||''}  type='date'
                            onChange={e => setInp({ ...inp, 检验日期: e.currentTarget.value}) } />
                </InputLine>
                <InputLine  label='下次定期检验日期' >
                    <Input  value={inp?.新下检日 ||''}  type='date'
                            onChange={e => setInp({ ...inp, 新下检日: e.currentTarget.value}) } />
                </InputLine>
                七、备注
                <InputLine  label='备注(可选的)' >
                    <Select inputSize="md" css={{minWidth:'140px',fontSize:'1.3rem',padding:'0 1rem'}}
                            value={ inp?.大备注  ||''}
                            onChange={e => setInp({ ...inp, 大备注: e.currentTarget.value||undefined}) }
                    >
                        <option></option>
                        <option>驾驶人员应持有效作业人员证。</option>
                        <option>本报告为复检报告，本次复检仅对上次不合格报告的不合格项进行复检，其余项目单项结论引用上次不合格报告中相对应项目的结论</option>
                    </Select>
                </InputLine>
                <TextArea  value={inp?.大备注 ||''} rows={4}
                           onChange={e => setInp({ ...inp, 大备注: e.currentTarget.value||undefined}) } />
            </InspectRecordLayout>
        );
    } );

/**不要重名了 ['附设装置名称','附设装置'] 可能莫名其妙报错的。台账snapshot.‘安装单位’等不能直接使用的，要本次最新:易变动。
 * */
const dbName设备概况 =[{desc:'防爆-气体/粉尘组别',name:'粉尘组'},{desc:'防爆-温度组别',name:'温度组'},
    {desc:'车架结构',name:'车架结构',type:'l',list:["三支点整体车架结构","四支点整体车架结构","铰接车架结构"]},
    {desc:'驾驶方式',name:'驾驶式',type:'l',list:["坐驾","站驾","步驾"]},
    {desc:'检验前设备状况',name:'前状况',type:'l',list:["正常", "不正常"]},{desc:'检验后设备状况',name:'后状况',type:'l',list:["正常", "不正常"]},
    {desc:'检验类别',name:'检验类别',type:'l',list:["首次检验", "定期检验"]},{desc:'试验条件',name:'试验条件',type:'l',list:["符合要求", "不符合要求"]},
    {desc:'检验意见通知书编号',name:'意见书号'},{desc:'整改反馈期限',name:'反馈期限',type:'d'},
];
/**注意这里的ref不是窗口<DIV ref={ref}>的哪一个;而是 React.useRef<InternalItemHandResult>(null)类似的传递数据和接口函数的,不是一个东西;
 * */
export const DeviceSurvey=
    React.forwardRef((
        { children, show ,alone=true,refWidth}:InternalItemProps,  ref
    ) => {
        const getInpFilter = React.useCallback((par: any) => {
            let fields={} as any;
            dbName设备概况.forEach(({name}:any, i:number)=> {
                fields[name] =par[name];
            });
            return fields;
        }, []);
        const {inp, setInp} = useItemInputControl({ ref });
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}
                                 alone={alone}  label={'二、设备概况'}>
                设备概况除了台账外还需要修改的部分:
                <LineColumn  column={3} >
                    {           /* 剔除最后一个”备注“要单独处理的 */
                        dbName设备概况.map(({name,desc,cb,type,unit,list} : any, i:number)=> {
                            // if(i>=dbName设备概况2.length-1)      return <React.Fragment key={i}></React.Fragment>;
                            if(cb?.edit){
                                return  cb.edit(inp,setInp);
                            }
                            else if(type==='l') return <InputLine key={i} label={desc}>
                                    <InputDatalist value={(inp?.[name]) || ''} datalist={list}
                                               onListChange={v => {
                                                   setInp({ ...inp, [name]:v || undefined});
                                               } } />
                                </InputLine>;
                            else if(type==='d') return  <InputLine key={i} label={desc}>
                                    <Input  value={inp?.[name] ||''}  type='date'
                                            onChange={e => setInp({ ...inp, [name]: e.currentTarget.value}) } />
                                </InputLine>;
                            else if(type==='b') return  <InputLine key={i} label={desc}>
                                <CheckSwitch  checked={inp?.[name] || false} onChange={e => setInp({...inp, [name]: inp?.[name]? undefined:true}) } />
                                </InputLine>;
                            else if(type==='m')  return <div key={i}>{desc}:
                                         <TextArea  value={inp?.[name] ||''} rows={4}
                                            onChange={e => setInp({ ...inp, [name]: e.currentTarget.value||undefined}) } />
                                    </div>;
                            else if(unit) return  <InputLine key={i} label={desc}>
                                    <SuffixInput  value={inp?.[name] ||''} onSave={txt=> setInp({...inp,[name]: txt || undefined })}
                                              type={type==='n'? "number": undefined}>{unit}</SuffixInput>
                                </InputLine>;
                            else return  <InputLine label={desc+`:`} key={i}>
                                    <Input  value={inp?.[name] ||''} type={type==='n'? "number": undefined}
                                            onChange={e => {
                                                setInp({...inp,[name]:e.currentTarget.value || undefined});
                                            } } />
                                </InputLine>;
                        })
                    }
                </LineColumn>
            </InspectRecordLayout>
        );
    } );

// const 默认仪器=[{n:'综合气象仪'},{n:'水准仪'},{n:'钢卷尺'},{n:'钢板尺'},{n:'万用表'},{n:'绝缘电阻仪'},{n:'接地电阻仪'},{n:'测距仪'},{n:'游标卡尺'},
//     {n:'经纬仪'},{n:'秒表'},{n:'力矩扳手'},{n:'测厚仪'},{n:'点温计'},{n:'全站仪'},{n:'手持式特斯拉计'},{n:'磁粉探伤仪'},{n:'应变应力测试仪'}];
//【注意】回调函数局限：若加<React.Fragment > 会导致<InputLine 内勤套render时刻无法穿透提供 props 给输入组件的：层次层级不配套，造成样式不一致问题！
const config仪器表=[['仪器设备名称','n',130],['型号规格','t',115],['仪器设备编号','i',115],
    ['开机后','o',65,(obj,setObj)=>{
        return <SelectHookfork value={ obj?.o ||''} onChange={e => setObj({ ...obj, o: e.currentTarget.value||undefined})}/>
    }],
    ['关机前','f',65,(obj,setObj)=>{
        return <SelectHookfork value={ obj?.f ||''} onChange={e => setObj({ ...obj, f: e.currentTarget.value||undefined})}/>
    }],
] as Each_ZdSetting[];

export const ItemInstrumentTable=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd}:InternalItemProps,  ref
    ) => {
        const breaks=[140,420,620];     //看内容调整: 更紧凑点的
        const headview=<Text variant="h5">
            一、主要检验仪器设备性能检查：“性能状态”一栏分为俩字段(1)开机后和(2)关机前。
        </Text>;
        const tailview=<>
            <Text>
                注：1、性能状态一栏中用“√”表示正常，用“×”表示不正常。
                <Text css={{display: 'flex', marginLeft:'2rem'}}>
                    2、若仪器设备性能状态不正常，应更换为性能状态正常的仪器设备，并填写在预留栏中。<br/>
                    3、新增使用的仪器设备应填写在预留栏中。<br/>
                    4、未使用的仪器设备可不填写。
                </Text>
            </Text>
        </>;
        const {render}=useRepTableEditor({ref,nestMd,show,alone,redId,
            config: config仪器表, table:'仪器表', column:3, breaks, label:'一、主要测量设备性能检查', headview,tailview,
        });
        return render;
    } );


const itemA观测=['观测表'];
const config观测表=[['项目编号','c',60],['观测内容','n',258],['判断标准','b',66],['观测数据','o',74,(obj,setObj)=>{
        return <SuffixInput  value={obj?.o ||''} onSave={txt=> setObj({...obj,o: txt || undefined })}>mm</SuffixInput>
    }],['测量结果','r',55],['检验结果','j',45,(obj,setObj)=>{
    return <SelectHookfork value={ obj?.j ||''} onChange={e => setObj({ ...obj, j: e.currentTarget.value||undefined}) }/>
}]] as Each_ZdSetting[];
export const 默认观测=[{c:'2.8(3) ①',n:'蓄电池金属盖或者非金属盖的金属部件与蓄电池带电部分之间的间隙',b:'30＜X'},
    {c:'2.8(3) ②',n:'如盖板和带电部分之间具有绝缘层时的间隙',b:'10 ≤ X'},
    {c:'2.10(5)',n:'充气轮胎胎面和胎壁的破裂和割伤长度',b:'25 ≥ X'},
    {c:'2.16(10)',n:'挡货架两个开口尺寸中的较小尺寸',b:'150 ≥x'},];
export const Observation=
    React.forwardRef(({ children, show ,alone=true,refWidth}:InternalItemProps,  ref
    ) => {
        const defvcbFunc = React.useCallback((par: any) => {
            const { 观测表 }=par||{};
            if(!观测表 || 观测表.length<1)   par.观测表=默认观测;
            return  par;
        }, []);
        const [getInpFilter]=useMeasureInpFilter(null,itemA观测,defvcbFunc);
        const {inp, setInp} = useItemInputControl({ ref });
        const headview=<Text variant="h5">
            八、观测数据及测量结果记录表；按照一行3个字段录入的：单位为mm;
        </Text>;
        const [render观测表]=useTableEditor({ inp, setInp,  headview,
            config: config观测表, table:'观测表', defaultV:默认观测, noDelAdd:true, fixColumn:3, column:6});
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}
                                 alone={alone}  label={'八、观测数据及测量结果记录表'}>
                {render观测表}
            </InspectRecordLayout>
        );
    } );


const config制动表=[['检验内容','n',208],['车辆速度（km/h）','s',82],['制动距离（m）','d',74,(obj,setObj)=>{
    return <SuffixInput  value={obj?.d ||''} onSave={txt=> setObj({...obj,d: txt || undefined })}>m</SuffixInput>
}],['判断标准（m）','b',70]] as Each_ZdSetting[];
export const 默认制动=[{n:'空载前进行车制动（往）'},{n:'空载前进行车制动（返）'},{n:'空载前进行车制动平均值'},
             {n:'空载后退行车制动（往）'},{n:'空载后退行车制动（返）'},{n:'空载后退行车制动平均值'}];
const itemA制动距离=['组别','制动表','空载前r','空载后r'];
export const Braking=
    React.forwardRef(({ children, show ,alone=true,refWidth}:InternalItemProps,  ref
    ) => {
        const defvcbFunc = React.useCallback((par: any) => {
            const { 制动表 }=par||{};
            if(!制动表 || 制动表.length<1)   par.制动表=默认制动;
            return  par;
        }, []);
        const [getInpFilter]=useMeasureInpFilter(null,itemA制动距离,defvcbFunc);
        const {inp, setInp} = useItemInputControl({ ref });
        const headview=<Text variant="h5">
           附录A:制动距离检测；按照一行3个字段录入的：
        </Text>;
        const [render制动表]=useTableEditor({inp, setInp,  headview,
                    config: config制动表, table:'制动表', defaultV:默认制动, noDelAdd:true, fixColumn:1, column:6});
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}
                                 alone={alone}  label={'附录A：制动距离检测'}>
                <InputLine  label='车辆组别:' >
                    <Select value={ inp?.组别  ||''} inputSize="md" css={{minWidth:'140px',fontSize:'1.3rem',padding:'0 1rem'}}
                            onChange={e => setInp({ ...inp, 组别: e.currentTarget.value||undefined}) }>
                        <option></option>
                        <option>A1</option>
                        <option>A2</option>
                        <option>C</option>
                    </Select>
                </InputLine>
                项目编号统一是：3.5(3) 的。
                {render制动表}
                <hr/>
                上表最后一列检验结果列拆出来：
                <InputLine label={`${默认制动[2].n}-检验结果`}>
                    <SelectHookfork value={ inp?.空载前r ||''}
                                    onChange={e => setInp({ ...inp, 空载前r: e.currentTarget.value||undefined}) }/>
                </InputLine>
                <InputLine label={`${默认制动[5].n}-检验结果`}>
                    <SelectHookfork value={ inp?.空载后r ||''}
                                    onChange={e => setInp({ ...inp, 空载后r: e.currentTarget.value||undefined}) }/>
                </InputLine>
            </InspectRecordLayout>
        );
    } );

export const config复检表=[['类别','c',30],['编号','no',84],['不合格内容','b',150],['复检结果','rs',50,(obj,setObj)=>{
    return <SelectHookfork value={ obj?.rs ||''} onChange={e => setObj({ ...obj, rs: e.currentTarget.value||undefined}) }/>
}],['复检日期','d',65,(obj,setObj)=>{
    return <Input  value={obj?.d ||''}  type='date' onChange={e => setObj({ ...obj, d: e.currentTarget.value}) } />
}]] as Each_ZdSetting[];
export const ItemRecheckResult=
    React.forwardRef((
        { children, show ,alone=true,repId,verId}:InternalItemProps,  ref
    ) => {
        const theme= useTheme();
        const impressionismAs =React.useMemo(() => {
            return setupItemAreaRoute({verId:verId!, repId:repId!, theme});
        }, [verId, repId, theme]);
        const getInpFilter = React.useCallback((par: any) => {
            const {unq} =par||{};
            return {unq};
        }, []);
        const {inp, setInp} = useItemInputControl({ ref });
        const {storage, setStorage} =React.useContext(EditStorageContext) as any;
        const 默认复检表 =React.useMemo(()=>itemResultUnqualified(storage, impressionismAs?.Item,{noCB: 特殊项目编码 }),
            [storage,impressionismAs?.Item]);
        const headview=<Text variant="h5">
            附录15  检验不合格项目内容
        </Text>;
        //不是真的默认不变的不能用  defaultV:默认复检表,
        const [renderTab]=useTableEditor({inp, setInp,  headview,
                  config: config复检表, table:'unq', defaultV:默认复检表, noDelAdd:true, fixColumn:2,maxRf:2,saveFixC:true});
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}
                                 alone={alone}  label={'附录15：检验不合格项目内容'} column={0}>
                <Button intent='primary' onPress={() =>{
                    let arrUnq=itemResultUnqualified(storage, impressionismAs?.Item,{noCB: 特殊项目编码 });
                    // let arrUnq22=itRes.failure.map((ts:any, i:number) => { return {no: ts,c: itRes[ts].iClass, b: itRes[ts].fdesc}; });
                    setStorage({...storage, unq:arrUnq});
                }}
                >依据记录来初始化本表默认值</Button>但不能重复初始化！
                <hr/>
                {renderTab}
            </InspectRecordLayout>
        );
    } );

